from maix import app , image , uart , camera , display , pinmap , gpio
import struct , pickle

threshold = [[]]
receive_flag = False
device1 = "/dev/ttyS0"          # 示例的串口名称                        此串口设备名称为串口0
uart1 = uart.UART(device1 , 115200)


def save_value(data):
    file_path = "/root/txt/threshold.txt"
    try:
        with open(file_path, "wb") as f:
            pickle.dump(data, f)
        print("Saved to:", file_path)
    except Exception as e:
        print("Write error:", e)

def Uart_Callback(uart , data):
    global threshold , receive_flag
    print("成功接收到数据")
    data_l = len(data)
    if data_l == 8:
        if data[0] == 0xbb:
            if data[1] == 0x00:
                values = struct.unpack('BBBBbbbb', data)          # 格式 'ii' 表示两个int
                threshold = [[values[2],values[3],values[4],values[5],values[6],values[7]]]
            if data[1] == 0x01:
                save_value(threshold)
                uart_send(uart1,0xcc,1)



def uart_send(serial:uart.UART,head,data):
    send_data = struct.pack("<Bh",head,data)
    serial.write(send_data)

cam = camera.Camera()
dis = display.Display()
uart1.set_received_callback(Uart_Callback)


while not app.need_exit():
    img = cam.read()

    if threshold:
        img.binary(threshold)

    dis.show(img)